from tortoise.expressions import Q
from app.core.redis_base import delete_keys
from app.core.crud import CRUDBase
from app.models import AppointmentCategory, GoodsSku, Goods
from app.models.appointment import AppointmentProject
from app.schemas.appointment import AppointmentProjectCreate,AppointmentProjectUpdate


class AppointmentProjectController(CRUDBase[AppointmentProject, AppointmentProjectCreate, AppointmentProjectUpdate]):
    def __init__(self):
        super().__init__(model=AppointmentProject)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        for item in data:
            if item["goods_id"]:
                goods = await Goods.filter(id=item["goods_id"]).first().values("id", "name")
                item['goods_info'] = goods
            if item["sku_id"]:
                sku = await GoodsSku.filter(id=item["sku_id"]).first().values("id", "sku_name","sku_level","sku_price")

                if sku and "sku_price" in sku:
                    sku["sku_price"] = float(sku["sku_price"])

                # 现在可以正常序列化为 JSON
                item['sku_info'] = sku
            item['label'] = f"{item['name']}/用时{item['interval']}分钟"
            item['value'] = item['id']
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self,request, obj_in: AppointmentProjectCreate):
        await self.create(obj_in=obj_in)
        await self.do_delete_redis(request)
        return True

    async def do_update(self,request, obj_in: AppointmentProjectUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        await self.do_delete_redis(request)
        return True

    async def do_update_good(self,good_id:int):
        objs = await self.model.filter(goods_id=good_id).values("id")
        update_data = {
            "goods_id": 0,
            "sku_id": 0,
        }
        await self.model.filter(id__in=[obj["id"] for obj in objs]).update(**update_data)
        return True

    async def do_delete(self,request, data_id: int):
        await self.remove(id=data_id)
        await self.do_delete_redis(request)
        return True

    async def level_list(self,type:int):
        objs = await self.model.filter(type=type).values("id", "name")
        data = []
        for obj in objs:
            data.append({
                "label":obj['name'],
                "value":obj['id'],
                "children":[]
            })
        return data

    @staticmethod
    async def do_delete_redis(request):
        await delete_keys("projects:*", request.state.redis)
        await delete_keys("dates:*", request.state.redis)
        await delete_keys("times:*", request.state.redis)
        await delete_keys("dates_ini:*", request.state.redis)
        await delete_keys("times_ini:*", request.state.redis)

    @staticmethod
    async def categorys():
        objs = await AppointmentCategory.all().values("id", "name")
        data = dict()
        for obj in objs:
            data[obj['id']] = obj['name']
        return data



appointment_project_controller =AppointmentProjectController()
